# -*- coding:utf-8 -*-
import re
import _locale
import sys

from lib.fileTools import getFileListByFilter

_locale._getdefaultlocale = (lambda *args: ['zh_CN', 'utf8'])

import fileinput

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(name)s %(levelname)s %(message)s",
    datefmt='%Y-%m-%d  %H:%M:%S %a'
)


class Formater:
    zn = '[\u4e00-\u9fa5，。（）、-]'
    en = '[A-Za-z0-9]'
    zn_en_zn = "({}+)\\s*({}+)\\s*({}+)".format(zn, en, zn)
    en_zn = "({}+)\\s*({}+)".format(en, zn)
    zn_en = "({}+)\\s*({}+)".format(zn, en)

    def isImage(self, text):
        # ![image-20200806150650689](https://gitee.com/gsunwu/blogs/raw/master/blogs-images/20200806150657.png)
        return re.search("!\\[.*?\\]\\(.*\\)", text)

    def isCodeBlock(self, text):
        """

        :param text:string
        :return:
        """
        return text.find("```")==0

    def formate(self, file):
        logging.info("formating file:{}".format(file))
        for line in fileinput.input(file, inplace=1):
            tline = line
            if self.isImage(line) or self.isCodeBlock(line) or self.isBreakLine(line):
                print(tline, end="")
                continue
            else:
                tline = self.formateLine(line)
                print(tline, end="")

        logging.info("{} has been successfully formated".format(file))

    def formateLine(self, line):
        # 处理 中文+英文+中文
        # r=(re.match(self.zn_en_zn,line)).groups()
        # print(r)
        tline = re.sub(self.zn_en_zn, r'\1 \2 \3', line)
        # 处理 英文+中文
        tline = re.sub(self.en_zn, r'\1 \2', tline)
        # 处理：中文+英文
        tline = re.sub(self.zn_en, r'\1 \2', tline)

        # 修复 java .lang.String Java1 .4
        tline = re.sub("({}+?)\\s*(\\.)\\s*([0-9A-Za-z])".format(self.en), r'\1\2\3', tline)

        # 修复 1 /4
        tline = re.sub("([0-9])\\s*(/)\\s*([0-9])", r'\1\2\3', tline)
        return tline

    def isBreakLine(self, line):
        return line.find('\n')==0


if __name__ == '__main__':
    #    获取指定文件夹下所有.md 文件
    if len(sys.argv) != 3:
        print("usage: python formaterMarkdown.py <dir> <file_name_patten>")
    else:
        logging.info("start application.....")
        files = getFileListByFilter(sys.argv[1], sys.argv[2])
        formater = Formater()
        for file in files:
            formater.formate(file)
        logging.info("exit with code 0")
